package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.mapper.UserRelationMapper;
import com.zhentao.pojo.UserRelation;
import com.zhentao.service.UserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserRelationServiceImpl implements UserRelationService {

    @Resource
    private UserRelationMapper userRelationMapper;

    @Override
    public boolean bindSubordinateUser(String parentUserId, String childUserId) {
        try {
            // 检查是否已经存在关系
            QueryWrapper<UserRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_user_id", parentUserId)
                    .eq("child_user_id", childUserId)
                    .eq("status", 1);

            UserRelation existingRelation = userRelationMapper.selectOne(queryWrapper);
            if (existingRelation != null) {
                log.warn("用户关系已存在: parentUserId={}, childUserId={}", parentUserId, childUserId);
                return false;
            }

            // 创建新的用户关系
            UserRelation userRelation = new UserRelation();
            userRelation.setParentUserId(parentUserId);
            userRelation.setChildUserId(childUserId);
            userRelation.setStatus(1);

            int result = userRelationMapper.insert(userRelation);
            log.info("绑定下级用户成功: parentUserId={}, childUserId={}", parentUserId, childUserId);
            return result > 0;

        } catch (Exception e) {
            log.error("绑定下级用户失败: parentUserId={}, childUserId={}", parentUserId, childUserId, e);
            return false;
        }
    }

    @Override
    public List<String> getSubordinateUsers(String parentUserId) {
        try {
            QueryWrapper<UserRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_user_id", parentUserId)
                    .eq("status", 1);

            List<UserRelation> relations = userRelationMapper.selectList(queryWrapper);
            return relations.stream()
                    .map(UserRelation::getChildUserId)
                    .collect(Collectors.toList());

        } catch (Exception e) {
            log.error("获取下级用户失败: parentUserId={}", parentUserId, e);
            return null;
        }
    }

    @Override
    public String getParentUser(String childUserId) {
        try {
            QueryWrapper<UserRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("child_user_id", childUserId)
                    .eq("status", 1);

            UserRelation relation = userRelationMapper.selectOne(queryWrapper);
            return relation != null ? relation.getParentUserId() : null;

        } catch (Exception e) {
            log.error("获取上级用户失败: childUserId={}", childUserId, e);
            return null;
        }
    }

    @Override
    public int getUserLevel(String userId) {
        try {
            String parentUserId = getParentUser(userId);
            if (parentUserId == null) {
                return 0; // 没有上级用户
            }

            String grandParentUserId = getParentUser(parentUserId);
            if (grandParentUserId == null) {
                return 1; // 一级下级
            }

            return 2; // 二级下级

        } catch (Exception e) {
            log.error("获取用户层级失败: userId={}", userId, e);
            return 0;
        }
    }

    @Override
    public boolean isSubordinateUser(String parentUserId, String childUserId) {
        try {
            QueryWrapper<UserRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_user_id", parentUserId)
                    .eq("child_user_id", childUserId)
                    .eq("status", 1);

            UserRelation relation = userRelationMapper.selectOne(queryWrapper);
            return relation != null;

        } catch (Exception e) {
            log.error("检查下级用户失败: parentUserId={}, childUserId={}", parentUserId, childUserId, e);
            return false;
        }
    }

    @Override
    public boolean unbindSubordinateUser(String parentUserId, String childUserId) {
        try {
            QueryWrapper<UserRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_user_id", parentUserId)
                    .eq("child_user_id", childUserId);

            UserRelation relation = userRelationMapper.selectOne(queryWrapper);
            if (relation == null) {
                log.warn("用户关系不存在: parentUserId={}, childUserId={}", parentUserId, childUserId);
                return false;
            }

            relation.setStatus(0); // 设置为无效
            int result = userRelationMapper.updateById(relation);
            log.info("解绑下级用户成功: parentUserId={}, childUserId={}", parentUserId, childUserId);
            return result > 0;

        } catch (Exception e) {
            log.error("解绑下级用户失败: parentUserId={}, childUserId={}", parentUserId, childUserId, e);
            return false;
        }
    }
}
